﻿using System.Web.Http;
using Umbraco.Core.Persistence;
using Umbraco.Web.Editors;
using Umbraco.Web.Mvc;
using UmbracoExtending.Dealer.Model;
using UmbracoExtending.Dealer.Model.Config;

namespace UmbracoExtending.Dealer.Controller
{
    /// <summary>
    /// 获取经销商配置信息，主要是地图的
    /// </summary>
    [PluginController("UmbracoDealer")]
    public class BackendDealerConfigurationController : UmbracoAuthorizedJsonController
    {

        /// <summary>
        /// 获取默认的配置信息
        /// </summary>
        /// <returns>返回配置信息</returns>
        [HttpGet]
        public DealerConfiguration Get()
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;
            var query = new Sql().Select("Id, MapPlatform, MapAppKey, ListView, ShowWarning")
                .From("[umbracoExtendingDealerConfig]");
            return db.FirstOrDefault<DealerConfiguration>(query);
        }

        /// <summary>
        /// 修改配置信息
        /// </summary>
        /// <param name="configuration">前端传入的配置信息</param>
        /// <returns>返回错误码</returns>
        [HttpPut]
        public ErrorResult Put(DealerConfiguration configuration)
        {
            var db = UmbracoContext.Application.DatabaseContext.Database;
            var query = new Sql().Select("Id, MapPlatform, MapAppKey, ListView, ShowWarning, SimpleMode, ShowTwoLayers")
                .From("[umbracoExtendingDealerConfig]");
            var origin = db.FirstOrDefault<DealerConfiguration>(query);
            string sql = "UPDATE [umbracoExtendingDealerConfig] SET [MapPlatform] = @0, [MapAppKey] = @1, [ListView] = @2, [ShowWarning] = @3 WHERE Id = 1";
            object[] param = new object[] {
                configuration.MapPlatform
                , configuration.MapAppKey
                , configuration.ListView == "y" ? "y" : "n"
                , "y" };
            int r = db.Execute(sql, param);
            if (r > 0)
            {
                if (!string.IsNullOrEmpty(origin.MapPlatform) 
                    && !origin.MapPlatform.Equals(configuration.MapPlatform))
                {
                    db.Execute("UPDATE [umbracoExtendingDealer] SET [IsMistake] = 'y'");
                }
                return new ErrorResult() { ErrorCode = 0 };
            }
            else
            {
                return new ErrorResult() { ErrorCode = -1, ErrorMsg = "不可知的错误" };
            }
        }
    }
}
